package com.ys.controller.api.storage;

import com.alibaba.fastjson.JSON;
import com.ys.config.MenuId;
import com.ys.entity.storage.TccFbaDeliverItem;
import com.ys.entity.storage.TccLogisticsComprehensive;
import com.ys.service.storage.TccLogisticsPlanService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author: fxz
 * @CreateTime: 2025-02-25
 * @Description: 物流计划单控制层
 * @Version: 1.0
 */
@Controller
@RequestMapping("/api/inter/tccLogisticsPlan")
public class ApiInterTccLogisticsPlanController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccLogisticsPlanController.class);

    @Autowired
    private CommonApiService<TccLogisticsComprehensive> commonApiService;

    @Autowired
    private TccLogisticsPlanService tccLogisticsPlanService;

    //菜单id
    private Long menuId = MenuId.TCC_LOGISTICSPLAN;

    //权限字符
    private final String PERMISSIONS_VIEW = "tccLogisticsPlan:view";
    private final String PERMISSIONS_SSMARK = "tccLogisticsPlan:ssmark";
    private final String PERMISSIONS_CXMARK = "tccLogisticsPlan:cxmark";
    private final String PERMISSIONS_PPMARK = "tccLogisticsPlan:ppMark";
    private final String PERMISSIONS_CORDER = "tccLogisticsPlan:cOrder";

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccLogisticsComprehensive setSeachSql(TccLogisticsComprehensive cond){
        cond
                .addLeftJoin("TCC_FbaDeliverItem B ON B.id = A.fbaDeliverItemId ")
                .addField("B.fbaBoxUpInfoId")
                .addLeftJoin("TCC_FbaBoxUpInfo E ON E.id = B.FbaBoxUpInfoId")
                .addField("E.boxUpBid")//FBA装箱单号
                .addField("E.fbaNo")//FBA编号
                .addField("E.fbaTrackNo")//FBA追踪编号
                .addField("E.fbaToken")//FbaToken
                .addField("E.fbaId")//FbaId
                .addField("E.fbaWarehouse")//FBA仓库
                .addField("E.fbaWarehouseAddr")//FBA仓库地址
                .addField("E.fbaAmount")//Fba费用
                .addLeftJoin("TCC_FbaBoxUp F ON F.bid = E.BoxUpBid ")
                .addField("F.packToken")//包装组Token
                .addField("F.packId")//包装组Id
                .addField("F.distributionBid")//配货清单号
                .addLeftJoin("TCC_FbaFeeDetails G ON G.sourceBid = B.pbid AND G.sourceType = 1")
                .addField("G.priceTranPredict boxPriceTranPredict")//实际物流费（总）
                .addField("G.weightReal")//实重
                .addField("G.weightVol")//抛重
                .addLeftJoin("TCC_FbaPlan J ON J.bid= A.FbaPlanBid ")
                .addField("J.bid fbaplanBid")//FBA计划单号
                .addField("J.shopId shopId")//店铺信息
                .addField("J.creationMethod")//下单方式
                .addField("J.declarationState")//是否报关
                .addField("J.deliverState")//发货计划
                .addField("J.vgsbm")//运营公司编码
                .addField("J.vgsJc")//运营公司简称
                .addField("J.shopName")//网店名称
                .addField("J.remark")//FBA计划单备注
                .addField("J.evenlyBoxNum")//均分箱数
                .addLeftJoin("TCC_FbaLogisticsMethod K ON K.sourceBid = B.pbid AND K.sourceType = 1")
                .addField("K.logsticsWay")//物流服务名称
                .addLeftJoin("TCC_FbaFeeDetails L ON L.sourceBid = J.bid AND L.sourceType = 0")
                .addField("L.priceTranPredict")//预估物流费（总）
                .addLeftJoin("TS_UserChange U ON U.Id = J.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS createUser")//制单人
                .addField("A.status _ys_status")
                .setOrderby("(E.fbaWarehouse +K.logsticsWay )");//联合排序
                ;
        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }


    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TccLogisticsComprehensive cond, String conditions){
        cond = setSeachSql(cond);
        String _ys_createTime = ConditionUtil.getConditionValue(conditions, "_ys_createTime");//物流计划创建时间
        if (_ys_createTime != null && _ys_createTime.length() > 0) {
            String[] timeDays = _ys_createTime.split(" ~ ");
            cond.where("A.createTime >= '" + timeDays[0] + "' and A.createTime <= '" + timeDays[1] + "'");
        }
        String _ys_status = ConditionUtil.getConditionValue(conditions, "_ys_status");//物流状态
        if (_ys_status != null && _ys_status.length() > 0 && !_ys_status .equals("1001")) {
            cond.where("A.status =" + _ys_status);
        }
        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }

    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/searchZb")
    @ResponseBody
    public LayuiTableVoJA searchZb(@ModelAttribute TccLogisticsComprehensive cond, String rowConditions){
        TccLogisticsComprehensive tccLogisticsComprehensive = JSON.parseObject(rowConditions, TccLogisticsComprehensive.class);
        TccFbaDeliverItem tccFbaDeliverItem = new TccFbaDeliverItem().setId(tccLogisticsComprehensive.getFbaDeliverItemId()).queryFirst();
        cond.addLeftJoin("TCC_FbaDeliverSon B ON B.Pbid = A.fbaDeliverBid ")
                .addField("B.boxNo")//箱号
                .addLeftJoin("TCC_FbaDeliverItem DD ON DD.id = B.FbaDeliverItemId ")
                .addLeftJoin("TCC_FbaBox D ON D.id = B.FbaBoxId ")
                .addField("(CONVERT(varchar(10), cast(D.BoxLong as float)) + '*' + CONVERT(varchar(10), cast(D.BoxWide as float))  + '*' + CONVERT(varchar(10), cast(D.BoxHigh as float))) dimensionsCase")//箱尺寸
                .addField("D.boxWeight")//箱重量
                .addLeftJoin("TCC_FbaBoxDetail C ON C.BoxId = D.id ")
                .addField("C.num")//箱中数量
                .addField("C.purchaseAmount priceIn")//商品采购价
                .addLeftJoin("TCC_FbaBoxUpItem H ON H.id = C.BoxUpItemId ")
                .addField("H.AverageBoxUpNum averageBoxNum")
                .addField("H.goodsLink goodsLink")
                .addField("H.averageBoxUpNum averageBoxUpNum")
                .addLeftJoin("TCC_FbaPlanItem I ON I.id = H.FbaPlanItemId")
                .addField("I.commodityCode,I.commodityName,I.sku,I.numStock,I.numPlanDeliver,I.isSign,I.signCode,I.annexFile,I.asin,I.fnSku,I.codeGoodsHs,I.nameGoodsCn")
                .addField("I.nameMaterialCn,I.weightPackage,I.vck,I.vkq,I.vhw,I.numApiDeliver")
                .addField("(CONVERT(varchar(19), cast(I.lengthPackage as float)) + '*' + CONVERT(varchar(19), cast(I.widthPackage as float))  + '*' + CONVERT(varchar(19), cast(I.heightPackage as float))) packageSize")
                .setOrderby("A.id DESC");//排序
        if (tccLogisticsComprehensive != null) {
            cond.where("DD.FbaBoxUpInfoId = " + tccFbaDeliverItem.getFbaBoxUpInfoId());
        }
        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }

    /*
     * 单独发货标记
     */
    @RequiresPermissions(PERMISSIONS_SSMARK)
    @RequestMapping("/ssmark")
    @ResponseBody
    public R ssmark(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        try {
            return tccLogisticsPlanService.ssmark(params);
        } catch (Exception e) {
            logger.error("单独发货标记出错：", e.getMessage(), e);
            return R.error("单独发货标记出错,原因如下:" + e.getMessage());
        }
    }

    /*
     * 单独发货标记选择渠道保存
     */
    @RequiresPermissions(PERMISSIONS_SSMARK)
    @RequestMapping("/ssmarkNew")
    @ResponseBody
    public R ssmarkNew(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        try {
            return tccLogisticsPlanService.ssmarkNew(params);
        } catch (Exception e) {
            logger.error("单独发货标记出错：", e.getMessage(), e);
            return R.error("单独发货标记出错,原因如下:" + e.getMessage());
        }
    }

    /*
     * 单独发货标记保存不选择渠道保存
     */
    @RequiresPermissions(PERMISSIONS_SSMARK)
    @RequestMapping("/ssmarkNew1")
    @ResponseBody
    public R ssmarkNew1(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        try {
            return tccLogisticsPlanService.ssmarkNew1(params);
        } catch (Exception e) {
            logger.error("单独发货标记出错：", e.getMessage(), e);
            return R.error("单独发货标记出错,原因如下:" + e.getMessage());
        }
    }

    /*
     * 重新发货标记
     */
    @RequiresPermissions(PERMISSIONS_CXMARK)
    @RequestMapping("/cxmark")
    @ResponseBody
    public R cxmark(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        try {
            return tccLogisticsPlanService.cxmark(params);
        } catch (Exception e) {
            logger.error("重新发货标记出错：", e.getMessage(), e);
            return R.error("重新发货标记出错,原因如下:" + e.getMessage());
        }
    }

    /*
     * 物流计划取消
     */
    @RequiresPermissions(PERMISSIONS_CXMARK)
    @RequestMapping("/qxPlan")
    @ResponseBody
    public R qxPlan(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        try {
            return tccLogisticsPlanService.qxPlan(params);
        } catch (Exception e) {
            logger.error("物流计划取消出错：", e.getMessage(), e);
            return R.error("物流计划取消出错,原因如下:" + e.getMessage());
        }
    }

    /*
     * 拼票发货标记判断
     */
    @RequiresPermissions(PERMISSIONS_PPMARK)
    @RequestMapping("/ppMark")
    @ResponseBody
    public R ppMark(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        try {
            return tccLogisticsPlanService.ppMark(params);
        } catch (Exception e) {
            logger.error("拼票发货标记出错：", e.getMessage(), e);
            return R.error("拼票发货标记出错,原因如下:" + e.getMessage());
        }
    }

    /*
     * 拼票发货标记发票号生成
     */
    @RequiresPermissions(PERMISSIONS_PPMARK)
    @RequestMapping("/ppMarkNew")
    @ResponseBody
    public R ppMarkNew(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        try {
            return tccLogisticsPlanService.ppMarkNew(params);
        } catch (Exception e) {
            logger.error("拼票发货标记出错：", e.getMessage(), e);
            return R.error("拼票发货标记出错,原因如下:" + e.getMessage());
        }
    }

    /*
     * 获取拼票预测数据
     */
    @RequiresPermissions(PERMISSIONS_PPMARK)
    @RequestMapping("/ppMarkTicket")
    @ResponseBody
    public R ppMarkTicket(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        try {
            return tccLogisticsPlanService.ppMarkTicket(params);
        } catch (Exception e) {
            logger.error("获取拼票预测数据：", e.getMessage(), e);
            return R.error("获取拼票预测数据,原因如下:" + e.getMessage());
        }
    }

    /*
     * 物流订单生成
     */
    @RequiresPermissions(PERMISSIONS_CORDER)
    @RequestMapping("/cOrder")
    @ResponseBody
    public R cOrder(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        try {
            return tccLogisticsPlanService.cOrder(params);
        } catch (Exception e) {
            logger.error("物流订单生成出错：", e.getMessage(), e);
            return R.error("物流订单生成出错,原因如下:" + e.getMessage());
        }
    }
}
